package com.cssy.yd.logic.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.byd.acegiext.domain.User;
import com.cssy.yd.logic.dao.LogicPriceDAO;
import com.cssy.yd.logic.dao.LogicWhmoveInwhDAO;
import com.cssy.yd.logic.dao.LogicWhmoveInwhItemDAO;
import com.cssy.yd.logic.dao.LogicWhmoveOutwhDAO;
import com.cssy.yd.logic.dao.LogicWhmoveOutwhItemDAO;
import com.cssy.yd.logic.entity.LogicPriceDO;
import com.cssy.yd.logic.entity.LogicWhAffDO;
import com.cssy.yd.logic.entity.LogicWhmoveInwhDO;
import com.cssy.yd.logic.entity.LogicWhmoveInwhItemDO;
import com.cssy.yd.logic.entity.LogicWhmoveOutwhDO;
import com.cssy.yd.logic.service.ILogicStockTransferEndService;
import com.cssy.yd.logic.service.ILogicWhAffStockService;
import com.plat.exception.SyBaseException;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.DateUtils;
import com.plat.util.GlobalResLoader;
import com.plat.util.IDCodeTypeUtil;
import com.plat.util.SessionUtil;
import com.yuendong.sy.po.code.SyCode;
import com.yuendong.sy.service.code.SyCodeType;
import com.yuendong.sy.service.code.impl.SyCodeService;

@Service("logicStockTransferEndService")
public class LogicStockTransferInServiceImpl implements ILogicStockTransferEndService{

	@Resource(name = "logicWhmoveOutwhDAO")
	private LogicWhmoveOutwhDAO logicWhmoveOutwhDAO;
	
	@Resource(name = "logicWhmoveOutwhItemDAO")
	private LogicWhmoveOutwhItemDAO logicWhmoveOutwhItemDAO;
	
	@Resource(name = "logicWhmoveInwhDAO")
	private LogicWhmoveInwhDAO logicWhmoveInwhDAO;
	
	@Resource(name = "logicWhmoveInwhItemDAO")
	private LogicWhmoveInwhItemDAO logicWhmoveInwhItemDAO;
	
	@Resource(name = "logicWhAffStockService")
	private ILogicWhAffStockService logicWhAffStockService;
	
	@Resource(name = "syCodeService")
	private SyCodeService syCodeService;
	
	@Resource(name = "logicPriceDAO")
	private LogicPriceDAO logicPriceDAO;
	
	@Override
	public SearchResult findListByExample(SearchConditions scs)
			throws SyBaseException {
		SearchResult rs=new SearchResult(scs);
		List<LogicWhmoveInwhDO>  list= logicWhmoveInwhDAO.find(scs);
		rs.setRecordCount(logicWhmoveInwhDAO.count(scs));
		rs.setResults(list);
		return rs;
	}

	@Override
	public Integer delete(String id, User user) throws SyBaseException {
		LogicWhmoveInwhDO basic=new LogicWhmoveInwhDO();
		basic.setDutime(new Date());
		basic.setDuuser(user.getName());
		basic.setId(id);
		basic.setRemoved(Short.parseShort("1"));
		logicWhmoveInwhItemDAO.deleteLogicWhmoveInwhItemDOByPrimaryKey(id);
		logicWhmoveInwhDAO.updateLogicWhmoveInwhDO(basic);
		return null;
	}

	@Override
	public Integer update(LogicWhmoveInwhDO t, User user) throws SyBaseException {
		t.setDuuser(user.getName());
		t.setDutime(new Date());
		return logicWhmoveInwhDAO.updateLogicWhmoveInwhDO(t);
	}

	@Override
	public LogicWhmoveInwhDO save(LogicWhmoveInwhDO t, User user)
			throws SyBaseException {
		Date date=new Date();
		t.setDuuser(user.getName());
		t.setDutime(new Date());
		t.setDcruser(user.getName());
		t.setDctime(date);
		logicWhmoveInwhDAO.insertLogicWhmoveInwhDO(t);
		return t;
	}

	@Override
	public LogicWhmoveInwhDO findListById(String id) throws SyBaseException {
		return logicWhmoveInwhDAO.findLogicWhmoveInwhDOByPrimaryKey(id);
	}
	
	@Override
	public void endsave(LogicWhmoveInwhDO curAP, HttpServletRequest request)
			throws SyBaseException {
		try{

			String oricode = request.getParameter("oricode");
			String addressInfos =request.getParameter("addressInfos");
			String intime=request.getParameter("intime");//发起日期
			String rkrq=request.getParameter("rkrq"); //接收入库日期
			List<LogicWhmoveInwhItemDO> axxlist=JSONArray.parseArray(addressInfos, LogicWhmoveInwhItemDO.class);
			if (curAP.getId() != null && !"".equals(curAP.getId())) {// 修改
				int rst=0;
				curAP.setDuuser(SessionUtil.getUser(request).getName());
				curAP.setDutime(new Date());
				curAP.setRkrq(DateUtils.stringToDate(rkrq));
				curAP.setIntime(DateUtils.stringToDate(intime));
				rst=logicWhmoveInwhDAO.updateLogicWhmoveInwhDO(curAP);
				if(rst==1){
					logicWhmoveInwhItemDAO.deleteLogicWhmoveInwhItemDOByOtherInWhId(curAP.getId());
					for(int i=0;i<axxlist.size();i++){
						axxlist.get(i).setOtherinwhid(curAP.getId());
						axxlist.get(i).setId(IDCodeTypeUtil.getId());
						logicWhmoveInwhItemDAO.insertLogicWhmoveInwhItemDO(axxlist.get(i));
					}
				}else{
					throw new SyBaseException("您修改的当前行数据已发生改变,请重新点开查看");
				}
			} else {// 新增
				SearchConditions scs = new SearchConditions();
				scs.addCondition("oricode", oricode, SearchCondition.OP_EQUAL);
				scs.addCondition("billstauts", "0,1,2", SearchCondition.OP_IN);
				int incount = logicWhmoveInwhDAO.count(scs);
				if(incount > 0){
					throw new SyBaseException("已有此调拨发起单未处理完的接收单单据，请先处理已有的单据");
				}		
				String id=IDCodeTypeUtil.getId();
				curAP.setOtherinwhcode(syCodeService.getCode("JS","JS",SyCode.DATE_YYMM,5));
				curAP.setId(id);
				curAP.setRkrq(DateUtils.stringToDate(rkrq));
				curAP.setIntime(DateUtils.stringToDate(intime));
				curAP.setDcruser(SessionUtil.getUser(request).getName());
				curAP.setDctime(new Date());
				logicWhmoveInwhDAO.insertLogicWhmoveInwhDO(curAP);
				for(int i=0;i<axxlist.size();i++){
					axxlist.get(i).setOtherinwhid(id);
					axxlist.get(i).setId(IDCodeTypeUtil.getId());
					logicWhmoveInwhItemDAO.insertLogicWhmoveInwhItemDO(axxlist.get(i));
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			throw new SyBaseException(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
		
	}

	@Override
	public void checkSave(LogicWhmoveInwhDO curAP, HttpServletRequest request)
			throws SyBaseException {
		try{
			if (curAP.getId() != null && !"".equals(curAP.getId())) {// 审核
				int rst=0;
				LogicWhmoveInwhDO lpwd = this.findListById(curAP.getId());
				List<LogicWhmoveInwhItemDO> lwlist=new ArrayList<LogicWhmoveInwhItemDO>();
				if(curAP.getBillstauts()==2){//二级审核
					if(lpwd.getBillstauts()==1){
						lpwd.setVersion(curAP.getVersion());
						lpwd.setBillstauts(curAP.getBillstauts());
						this.update(lpwd, SessionUtil.getUser(request));
					}else{
						throw new SyBaseException("当前单据未在您审核权限内");
					}
					
				}
				if(curAP.getBillstauts()==3){//三级审核
					if(lpwd.getBillstauts()==1||lpwd.getBillstauts()==2){
						String addressInfos =request.getParameter("addressInfos");
						List<LogicWhmoveInwhItemDO> axxlist=JSONArray.parseArray(addressInfos, LogicWhmoveInwhItemDO.class);

			 			List<LogicWhmoveOutwhDO> outwhlist = new ArrayList<LogicWhmoveOutwhDO>();
			 			LogicWhmoveOutwhDO outwh = null;
			 			Double pressQuantity = Double.parseDouble("0");  //本次接收数量（所有物料之和）
			 			Double prewsquantity = Double.parseDouble("0"); //本次未收数量（所有物料之和）
			 			if(axxlist != null && axxlist.size() > 0){
							for (LogicWhmoveInwhItemDO initem : axxlist) {
								initem.setHisQuantity((initem.getHisQuantity()==null ? 0 : initem.getHisQuantity()) + (initem.getQuantity()==null?0:initem.getQuantity()));
								initem.setUnQuantity((initem.getUnQuantity()==null ? 0 : initem.getUnQuantity()) - (initem.getQuantity()==null ? 0 : initem.getQuantity()));
								initem.setQuantity(initem.getQuantity()==null ? 0: initem.getQuantity());  //本次接收数量
								pressQuantity += initem.getQuantity();
								prewsquantity += initem.getUnQuantity();
							}
						}
						lpwd.setVersion(curAP.getVersion());
						lpwd.setBillstauts(curAP.getBillstauts());
						
						//获取同一发起单号对应的已接收数量
						SearchConditions scs1 = new SearchConditions();
						scs1.addCondition("lwi.oricode", curAP.getOricode(), SearchCondition.OP_EQUAL);
						scs1.addCondition("lwi.billstauts", "3", SearchCondition.OP_EQUAL);
						Double yjsQuantity = logicWhmoveInwhItemDAO.findYjsQuantityByOricode(scs1);  //历史已接收总数量

						//获取此发起单号的发起数量
						SearchConditions scs2 = new SearchConditions();
						scs2.addCondition("lwo.billstatus", "3", SearchCondition.OP_EQUAL);
						scs2.addCondition("lwo.otheroutwhcode", curAP.getOricode(), SearchCondition.OP_EQUAL);
						Double fqQuantity =  logicWhmoveOutwhItemDAO.findFqQuantityByOtheroutwhid(scs2);  //发起单发起总数量
						Double hiswsQuantity = Double.parseDouble("0");//历史未接收数量
						
						SearchConditions scs3 = new SearchConditions();
						scs3.addCondition("billstatus", "3", SearchCondition.OP_EQUAL);
						scs3.addCondition("otheroutwhcode", curAP.getOricode(), SearchCondition.OP_EQUAL);
						outwhlist = logicWhmoveOutwhDAO.find(scs3);
						if(outwhlist!=null&&outwhlist.size()>0){  //发起单
							outwh = outwhlist.get(0);
						}
						
						if(yjsQuantity == null||yjsQuantity==0){
							yjsQuantity = Double.parseDouble("0.0");
			 			}
						hiswsQuantity = new BigDecimal(fqQuantity.toString()).subtract(new BigDecimal(yjsQuantity.toString())).doubleValue();	//	历史未接收总数量
						if(pressQuantity.doubleValue() < hiswsQuantity.doubleValue()) {
			 				if(outwh.getId()!=null){
			 					outwh.setIntype(Short.parseShort("1"));  //根据接收情况改变发起单中的物料接收状态
			 				}
			 			} else if(pressQuantity.doubleValue() == hiswsQuantity.doubleValue()){
			 				if(outwh.getId()!=null){
			 					outwh.setIntype(Short.parseShort("2"));
			 				}
			 			} else if(pressQuantity.doubleValue() > hiswsQuantity.doubleValue()) {
			 				throw new SyBaseException("您本次接收数量大于历史未接收数量！");
			 			}

			 			int j = logicWhmoveOutwhDAO.updateLogicWhmoveOutwhDO(outwh);
						if(j < 0){
							throw new SyBaseException("提交失败");
						}
						rst=this.update(lpwd, SessionUtil.getUser(request));
						for (int i = 0; i < axxlist.size(); i++) {
							logicWhmoveInwhItemDAO.updateLogicWhmoveInwhItemDO(axxlist.get(i));
						}
						if(rst==1){
							lwlist=logicWhmoveInwhItemDAO.findItemListByLogicWhmoveInwhId(lpwd.getId());
							if(lwlist.size()>0){
								for(int i=0;i<lwlist.size();i++){
									LogicWhAffDO lwhaff=new LogicWhAffDO();
									lwhaff.setBillCode(lpwd.getOtherinwhcode());
									lwhaff.setBillType("JS");
									lwhaff.setWhCode(lpwd.getOutwhcode());
									lwhaff.setWhname(lpwd.getOutwhname());
									lwhaff.setCode(lwlist.get(i).getCode());
									lwhaff.setName(lwlist.get(i).getName());
									lwhaff.setSpec(lwlist.get(i).getSpec());
									lwhaff.setBatch(lwlist.get(i).getBatch());
						    		lwhaff.setBrand(lwlist.get(i).getBrand());
									lwhaff.setStatus("5");
									lwhaff.setUnit(lwlist.get(i).getUnit());
									lwhaff.setQuantity(-lwlist.get(i).getQuantity());
									lwhaff.setDcruser(SessionUtil.getUser(request).getName());
									lwhaff.setDctime(new Date());
								//	lwhaff.setHubCode(lwlist.get(i).getHubcode());
								//	lwhaff.setHubName(lwlist.get(i).getHubname());
									lwhaff.setJunit(lwlist.get(i).getJunit());
									lwhaff.setJquantity(-lwlist.get(i).getJquantity());
									lwhaff.setBzq(lwlist.get(i).getBzq());
									lwhaff.setYxq(lwlist.get(i).getYxq());
									lwhaff.setScrq(lwlist.get(i).getScrq());
									//减少在途库存
									if (lwlist.get(i).getQuantity() != null && !"".equals(lwlist.get(i).getQuantity()) && lwlist.get(i).getQuantity() > 0 )
										logicWhAffStockService.updateWhAffstockQuantity(lwhaff, SessionUtil.getUser(request),false);
									
									LogicWhAffDO lwhaff1=new LogicWhAffDO();
									lwhaff1.setBillCode(lpwd.getOtherinwhcode());
									lwhaff1.setBillType("JS");
									lwhaff1.setWhCode(lpwd.getWhcode());
									lwhaff1.setWhname(lpwd.getWhname());
									lwhaff1.setUnit(lwlist.get(i).getUnit());
									lwhaff1.setCode(lwlist.get(i).getCode());
									lwhaff1.setName(lwlist.get(i).getName());
									lwhaff1.setSpec(lwlist.get(i).getSpec());
									lwhaff1.setBrand(lwlist.get(i).getBrand());
									lwhaff1.setStatus(lwlist.get(i).getStatus());
									lwhaff1.setQuantity(lwlist.get(i).getQuantity());
									lwhaff1.setBatch(lwlist.get(i).getBatch());
									lwhaff1.setDcruser(SessionUtil.getUser(request).getName());
									lwhaff1.setDctime(new Date());
							//		lwhaff.setHubCode(lwlist.get(i).getHubcode());
							//		lwhaff1.setHubName(lwlist.get(i).getHubname());
									lwhaff1.setJunit(lwlist.get(i).getJunit());
									lwhaff1.setJquantity(lwlist.get(i).getJquantity());
									lwhaff1.setBzq(lwlist.get(i).getBzq());
									lwhaff1.setYxq(lwlist.get(i).getYxq());
									lwhaff1.setScrq(lwlist.get(i).getScrq());
									if(lwlist.get(i).getPrice()==null||"".equals(lwlist.get(i).getPrice())||lwlist.get(i).getPrice()<=0){
										SearchConditions scs = new SearchConditions();
										scs.addCondition("wh_code", lpwd.getOutwhcode(),SearchCondition.OP_EQUAL);
										scs.addCondition("code", lwlist.get(i).getCode(),SearchCondition.OP_EQUAL);
										List<LogicPriceDO> lp=logicPriceDAO.find(scs);
										if(lp.size()>0){
											if(lp.get(0).getSumprice()!=null&&lp.get(0).getSumprice()>0){
												lwhaff1.setPrice(lp.get(0).getSumprice());
											}else{
												throw new SyBaseException("您没有填写单价,并且查不到该天物料的平均价格为0！入库失败！请填写物料价格");
											}
										}else{
											throw new SyBaseException("您没有填写单价,并且查不到该天物料的平均价格！入库失败！请填写物料价格");
										}
									}else{
										lwhaff1.setPrice(lwlist.get(i).getPrice());
									}
										logicWhAffStockService.updateWhAffstockQuantity(lwhaff1, SessionUtil.getUser(request),true);
								}
							}
						}else{
							throw new SyBaseException("您修改的当前行数据已发生改变,请重新点开查看");
						}
					}else{
						throw new SyBaseException("当前单据未在您审核权限内");
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			throw new SyBaseException(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
	}

	@Override
	public Integer deleteBizRemoved(String id) throws SyBaseException {
		// TODO Auto-generated method stub
		return null;
	}
}
